package org.jgs1904.controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.jgs1904.bean.ResultBean;
import org.jgs1904.entity.User;
import org.jgs1904.service.UserService;
import org.jgs1904.service.impl.UserServiceImpl;
import org.jgs1904.util.FileUploadUtil;

import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Constants;

/**
 * 用户控制器
 * 
 * @author junki
 * @date 2020年3月26日
 */
@WebServlet("/user")
public class UserController extends DispatcherController {

	private static final long serialVersionUID = -9131206594803720497L;

	private UserService userService = new UserServiceImpl();

	/**
	 * 注册方法
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void regist(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		// 将实体属性从map集合封装到实体对象
		User user = new User();
		try {
			BeanUtils.populate(user, FileUploadUtil.upload(request));
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		
		// 表单验证
		if (StringUtils.isAnyBlank(user.getNickname(), user.getUsername(), user.getPassword())) {
			request.setAttribute("message", "昵称、用户名和密码不能为空！");
			request.setAttribute("user", user);
			request.getRequestDispatcher("/user/regist.jsp").forward(request, response);
			return;
		}

		// 判断用户名是否已经存在
		User result = null;
		try {
			result = userService.getOne(User.builder().username(user.getUsername()).build());
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		if (result != null) {
			request.setAttribute("user", user);
			request.setAttribute("message", "用户名已存在，请更换用户名！");
			request.getRequestDispatcher("/user/regist.jsp").forward(request, response);
			return;
		}
		
		// 保存用户信息
		try {
			result = userService.add(user);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (result != null) {
			response.sendRedirect(request.getContextPath() + "/user/login.jsp");
		} else {
			request.setAttribute("user", user);
			request.setAttribute("message", "注册失败！请重试！");
			request.getRequestDispatcher("/user/regist.jsp").forward(request, response);
		}
	}

	/**
	 * 	登录方法
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		// 获取验证码
		String captcha = request.getParameter("captcha");
		//System.out.println("用户验证码：" + captcha);
		String code = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		//System.out.println("正确验证码：" + code);
		
		// 获取用户实体类的参数
		User user = new User();

		try {
			BeanUtils.populate(user, request.getParameterMap());
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		
		// 判断验证码
		if (StringUtils.isBlank(captcha)) {
			request.setAttribute("message", "验证码不能为空！");
			request.setAttribute("user", user);
			request.getRequestDispatcher("/user/login.jsp").forward(request, response);
		} else if (!code.equalsIgnoreCase(captcha)) {
			request.setAttribute("message", "验证码错误！");
			request.setAttribute("user", user);
			request.getRequestDispatcher("/user/login.jsp").forward(request, response);
		}

		User result = null;
		try {
			result = userService.getOne(user);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (result != null) {
			request.getSession().setAttribute("onlineUser", result);
			response.sendRedirect(request.getContextPath() + "/post?method=page");
		} else {
			request.setAttribute("message", "用户名或密码错误！");
			request.setAttribute("user", user);
			request.getRequestDispatcher("/user/login.jsp").forward(request, response);
		}
	}
	
	/**
	 * 	退出登录
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.getSession().removeAttribute("onlineUser");
		response.sendRedirect(request.getContextPath());
	}
	
	/**
	 *  检查用户名是否重复
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	public void checkUsername(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		String username = request.getParameter("username");
		
		User result = null;
		try {
			result = userService.getOne(User.builder().username(username).build());
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		if (result != null) {
			ResultBean resultBean = ResultBean.builder().code("200").message("error").build();
			response.getWriter().print(JSON.toJSONString(resultBean));
		} else {
			ResultBean resultBean = ResultBean.builder().code("200").message("ok").build();
			response.getWriter().print(JSON.toJSONString(resultBean));
		}
		
	}

}
